<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocketTest客户端</title>
</head>

<body>
    
        <h4>客户端输入：</h4>
        <textarea id = "message" name="message" style="width: 200px;height: 100px"></textarea>
        <br/>
        <input type="button" value="发送到服务器" onclick="sendMessage()" />
    
        <h4>服务器返回消息：</h4>
        <textarea id = "responseText" name="message" style="width: 1100px;height: 100px"></textarea>
        <br/>
        <input type="button" onclick="clearMessage()" value="清除数据">
 <script type="text/javascript">
    var webSocket;
    if(window.WebSocket){
        webSocket = new WebSocket("ws://127.0.0.1:9688/websocket");
        //客户端收到服务器的方法，这个方法就会被回调
        webSocket.onmessage = function (ev) {
            debugger
            var contents = document.getElementById("responseText");
            contents.value = contents.value +"\n"+ ev.data;
        }
        webSocket.onopen = function (ev) {
            var contents = document.getElementById("responseText");
            contents.value = "与服务器端的websocket连接建立";
            var data = '{code:10003,nick:"张三","room":"push_1001"}';
            webSocket.send(data);
        }
        webSocket.onclose = function (ev) {
            debugger
            var contents = document.getElementById("responseText");
            contents.value =  contents.value +"\n"+ "与服务器端的websocket连接断开";
        }
    }else{
        alert("该环境不支持websocket")
    }
 
    function sendMessage() {
        if(window.webSocket){
            if(webSocket.readyState == WebSocket.OPEN){
                var data= '{"code":10004,"mess":"'+document.getElementById("message").value+'","room":"push_1001"}';
                webSocket.send(data);
            }
        }
    }
    
    function clearMessage(){
        document.getElementById('responseText').value='';
    }
    
</script>   
</body>
</html>